<?php

class TicketsController extends AppController {


/**
 * Uses array
 *
 * @var array
 */
    public $uses = array('Ticket');

/**
 * Helpers
 *
 * @var array
 **/
  public $components = array('RequestHandler', 'SendMail');
  public $helpers = array('Html', 'Form', 'Paginator', 'Js' => array('Jquery'), 'Slashow');

/**
 * Pagination
 *
 * @var array
 **/
  public $paginate = array(
      'limit' => 15,
      'order' => array(
          'Ticket.created' => 'desc'
      )
  );
    
  public function beforeFilter() {
      parent::beforeFilter();
      $this->loadModel("Country");
      $this->loadModel("City");
      $this->loadModel("Setting");
      $this->loadModel("Enquiry");
  }

/**
 * @method: index
 * @purpose: list of all tickets
 * @param none
 * @return void
 **/
  public function admin_index() {
      $tickets = $this->paginate('Ticket');
      $this->set('tickets', $tickets);
  }
    
/**
 * @method: enquiry
 * @purpose: submit an enquiry
 * @param none
 * @return void
 **/
  public function enquiry() {
      if ($this->request->is('post')) {
          $this->Emstraining = $this->Components->load('Emstraining');
          $s_id = $this->Emstraining->rand_string("ticket");
          
          $this->request->data['Ticket']['key'] = $s_id;
          $this->request->data['Ticket']['sla'] = 1;
          $userID = $this->Auth->user('id');
          if(isset($userID)){
              $this->request->data['Ticket']['customer_id'] = $userID;
          }
          
          if ($this->Ticket->save($this->request->data)) {
              $ticket_id = $this->Ticket->id;
              /*** sending confirmation mail to customer  **/
              $array_values['CUSTOMER_NAME'] = $this->request->data['Ticket']['first_name'].' '.$this->request->data['Ticket']['last_name'];
              $array_values['TICKET_ID'] = $this->request->data['Ticket']['key'];

              $this->SendMail->send_mail("1", $this->request->data['Ticket']['email'],"Ticket ID #{$this->request->data['Ticket']['key']} :".$this->request->data['Ticket']['subject'],$array_values);

              /** sending notified mail to admin **/
              $to = Setting::get_option('EMAIL_PARSING');
              $array_values['LINK'] = Router::url(array('controller'=>'tickets', 'action'=>'view', $ticket_id, 'admin' => true), true);
              $this->SendMail->send_mail("2", $to,"Enquiry Ticket submitted by customer",$array_values);

              $this->Session->setFlash('Ticket was saved successfully.');
              $this->redirect(array('controller' => 'tickets', 'action' => 'enquiry'));
          } else {
              $this->Session->setFlash('Unable to save your ticket. please try again');
          }
      }
      if($this->Auth->user('id')&&$this->Auth->user('indentify')=="customer"){
          $this->loadModel("Customer");
          $this->set("customer",  $this->Customer->read(null,$this->Auth->user('id')));
      }
      $this->loadModel("Country");
      $this->set("countries",  $this->Country->get_list());
      
}
    
/**
 * @method: detail
 * @purpose: detail of enquiry ticket
 * @param none
 * @return void
 **/
  public function admin_view($id = null) {
      $this->Ticket->id = $id;
      $ticket = $this->Ticket->read();

      $isViewed = $ticket['Ticket']['viewed'];
      if($isViewed == 0){
          $this->Ticket->set(array(
              'viewed' => 1
          ));
          $this->Ticket->save();
      }
      
      $message_subject = array(); 
      if(!empty($ticket['TicketMessage'])){
           foreach($ticket['TicketMessage'] as $key => $values){
                $subject[] = $values['subject'];
           }
           $diff_sub = array_unique($subject);
           
           foreach($diff_sub as $sub){
                 $header = $this->Ticket->TicketMessage->find('first', array(
                                                                  'conditions' => array(
                                                                      'AND' => array(
                                                                          'TicketMessage.subject' => $sub, 
                                                                          'TicketMessage.ticket_id' => $id
                                                                        )
                                                                    ),
                                                                    'recursive' => -1
                                                                )
                                                            );
                 $content = $this->Ticket->TicketMessage->find('all', array(
                                                                  'conditions' => array(
                                                                      'AND' => array(
                                                                          'TicketMessage.subject' => $sub, 
                                                                          'TicketMessage.ticket_id' => $id
                                                                        )
                                                                    ),
                                                                    'recursive' => -1,
                                                                    'order' => array('TicketMessage.created DESC')
                                                                )
                                                            );
            $message_subject[] = array('Header' => $header, 'Content' => $content);
           }
      }
      $this->set('messages', $message_subject);
      $this->set('ticket', $ticket);
  }
  
/**
 * @method: reply
 * @purpose: reply to enquiry ticket
 * @param none
 * @return void
 **/
  public function admin_reply($id = null, $msgID = null){
      $this->layout = false;
      if ($this->request->is('post') || $this->request->is('put')) {

          //pr($this->request->data); die('you are here');
          $tID = $this->request->data['TicketMessage']['ticket_id'];
          if ($this->Ticket->TicketMessage->save($this->request->data)) {
              $message_id = $this->Ticket->TicketMessage->id;
         	    $tickets = $this->Ticket->find('first', array('conditions' => array('Ticket.id' => $this->request->data['TicketMessage']['ticket_id']), 'recursive' => -1));
              $array_values = array();
              $array_values['CUSTOMER_NAME'] = $tickets['Ticket']['first_name'].' '.$tickets['Ticket']['last_name'];
              $array_values['MESSAGE_CONTENT'] = $this->request->data['TicketMessage']['content'];
              if(isset($this->data['TicketMessage']['attachment'])){
                  $array_values['ATTACHMENT'] = WWW_ROOT . 'img' . DS . 'ticket' . DS . 'attachment' . DS .$this->request->data['TicketMessage']['attachment']['name'];
              }
              $array_values['REPLY_TICKET_LINK']=Router::url(array('controller'=>'tickets','action'=>'customer_reply',$tickets['Ticket']['key'], $message_id, 'admin' => false), true);

              $this->SendMail->send_mail("3", $tickets['Ticket']['email'], "Ticket ID #{$tickets['Ticket']['key']} :".$this->data['TicketMessage']['subject'],$array_values);

              $user = $this->Auth->user('id');
              $this->Ticket->checkSla($this->request->data['TicketMessage']['ticket_id'], $user);
          
              $this->Session->setFlash(__('The message has been sent'));
              $this->redirect(array('action' => 'view', $tID));
          } else {
              $this->Session->setFlash(__('The message could not be send. Please, try again.'));
          }
      } else {
          if($msgID){
              $ticket = $this->Ticket->TicketMessage->read(null, $msgID);
              $this->request->data['TicketMessage']['ticket_id'] = $ticket['TicketMessage']['ticket_id'];
              $this->request->data['TicketMessage']['name'] = $this->Auth->user('username');
              $this->request->data['TicketMessage']['subject'] = $ticket['TicketMessage']['subject'];
              $this->request->data['Ticket']['key'] = $ticket['Ticket']['key'];
              $flag = 1;
          }else{
              $ticket = $this->Ticket->read(null, $id);
              $this->request->data['TicketMessage']['ticket_id'] = $ticket['Ticket']['id'];
              $this->request->data['TicketMessage']['name'] = $this->Auth->user('username');
              $this->request->data['TicketMessage']['subject'] = $ticket['Ticket']['subject'];
              $this->request->data['Ticket']['key'] = $ticket['Ticket']['key'];
              $flag = 0;
          }
          $this->set('flag', $flag);
      }
  }
  
/**
 * @method: change_status
 * @purpose: change status of enquiry ticket
 * @param none
 * @return void
 **/
  public function admin_change_status($id = null) {
      if ($this->request->is('post') || $this->request->is('put')) {
          $this->Ticket->save($this->request->data);

          $this->request->data['TicketReason']['ticket_id'] = $this->request->data['Ticket']['id'];
          $this->request->data['TicketReason']['status'] = $this->request->data['Ticket']['status'];
          $this->request->data['TicketReason']['previous'] = $this->request->data['Ticket']['previous'];
          $this->Ticket->TicketReason->save($this->request->data);
          $this->redirect(array('action' => 'view', $this->request->data['Ticket']['id']));
      }else{
          $ticket = $this->Ticket->read(null, $id);
          $this->request->data['Ticket']['id'] = $id;
          $this->request->data['Ticket']['status'] = $ticket['Ticket']['status'];
          $this->request->data['Ticket']['previous'] = $ticket['Ticket']['status'];
      }
	}
  
/**
 * @method: admin_reply
 * @purpose: replying to Ticket
 * @param none
 * @return void
 **/
  public function admin_forward_message($message_id = null, $email = null) {
      $this->autoRender = false;
 	    if(!empty($message_id)){
          $tickets = $this->Ticket->TicketMessage->find('first', array('conditions' => array('TicketMessage.id' => $message_id)));
          $array_values = array();
          $array_reply = array();

          $array_values['CUSTOMER_NAME'] = $tickets['Ticket']['first_name'].' '.$tickets['Ticket']['last_name'];
          $array_values['MESSAGE_CONTENT'] = $tickets['TicketMessage']['content'];
          /*if(isset($tickets['TicketMessage']['attachment'])){
              $array_values['ATTACHMENT'] = $this->data['TicketMessage']['attachment']['name'];
          }
          $array_reply['REPLYTO'] = $this->data['TicketMessage']['replyTo'];
          */
          $array_values['REPLY_TICKET_LINK']=Router::url(array('controller'=>'tickets','action'=>'customer_reply',$tickets['Ticket']['key'], 'admin' => false), true);


          //$this->SendMail->send_mail("TICKET_TEMPLATE",$email,"Ticket ID #{$tickets['Ticket']['key']} :".$tickets['TicketMessage']['subject'],$array_values);
          echo "Message has been forwarded successfully.";
          exit;
      }else{
          echo 'Message has not been forwarded, Please try later.';
          exit;
      }
  }
  
/**
 * @method: admin_delete
 * @purpose: delete message of ticket
 * @param none
 * @return void
 **/
  public function admin_delete($id = null) {
     $this->autoRender = false;
     $ticket = $this->Ticket->TicketMessage->find('first', array('conditions' => array('TicketMessage.id' => $id)));
     $ticket_id = $ticket['TicketMessage']['ticket_id'];
     $this->Ticket->TicketMessage->delete($id);
     $this->redirect(array('controller'=>'tickets','action'=>'view', 'admin' => true, $ticket_id));
  }
       
/**
 * @method: customer_reply
 * @purpose: replying to Ticket
 * @param none
 * @return void
 **/
  public function customer_reply($id = null, $message_id = null) {
    
    if($this->request->is('post') || $this->request->is('put')) {

          if($this->Ticket->TicketMessage->save($this->data)) {
                            
              $this->request->data['Ticket']['id'] = $this->data['TicketMessage']['ticket_id'];
              $this->request->data['Ticket']['sla'] = $this->data['TicketMessage']['sla'] + 1;
              $this->Ticket->save($this->request->data);
              
              $this->Session->setFlash(__('Thanks for Contacting Us. We will get back to you soon.', true));                		
              $this->redirect(array('controller' => 'tickets', 'action' => 'enquiry'));
          }
    } else {
        if(empty($id)){
              $this->redirect(array('controller' => 'tickets', 'action' => 'enquiry'));
        }else{
      	      $ticket = $this->Ticket->find('first', array('conditions' => array('Ticket.key' => $id), 'recursive' => -1));
              if(empty($ticket)) {
                  $this->redirect(array('controller' => 'tickets', 'action' => 'enquiry'));
              }
       	      $ticket_message = $this->Ticket->TicketMessage->find('first', array('conditions' => array('TicketMessage.id' => $message_id), 'recursive' => -1));
              if(!empty($ticket_message['TicketMessage']['subject'])){
                  $this->request->data['TicketMessage']['subject'] = $ticket_message['TicketMessage']['subject'];
              }else{
                  $this->request->data['TicketMessage']['subject'] = $ticket['Ticket']['subject'];
              }
              
              $username = $ticket['Ticket']['first_name'].' '.$ticket['Ticket']['last_name'];
              $this->set('username' ,$username);
  
              $this->set('tickets', $ticket);
              $this->request->data['TicketMessage']['ticket_id'] = $ticket['Ticket']['id'];
        }
    }
  }     
    
    public function cron_ticket(){
        $this->autoRender=false;
        $this->Mailbox = $this->Components->load('Mailbox');
        pr($this->Mailbox); die('>>>>>>>>>');
        $emails = $this->Mailbox->get_mails('ALL');
        
        $last_email_id = $this->Setting->get_option('LAST_EMAIL_ID');
        $number_email = count($emails);
        if($number_email > $last_email_id){
            //$this->Option->save_option('LAST_EMAIL_ID',$number_email);
            for($i=$last_email_id+1;$i<=$number_email;$i++){
                $email = $this->Mailbox->get_mail($i);
                pr($email);die;
                $this->process_email($email);
            }
            $this->Setting->save_option('LAST_EMAIL_ID',$number_email);
        }
    }
    
    public function process_email($email){
        $check = 0;
        $str = explode('ticket key #', $email['subject']);
        if(isset($str[1])){
            $ticket_key = $str[1];
            $email_cus = $email['from']['address'];
            $ticket = $this->Ticket->find('first',array('conditions'=>array('key'=>$ticket_key,'email'=>$email_cus)));
            if(!empty($ticket)){
                $content =   $email['message'];
                $data= array(
                    'ticket_id'=>$ticket['Ticket']['id'],
                    'from'=>'User',
                    'subject'=>"RE :".$email['subject'],
                    'content'=>$content,
                    'created'=>  date('Y-m-d H:i:s')
                );
                //pr($data);die;
                $this->loadModel('TicketMessage');
                $this->TicketMessage->create();
                $this->TicketMessage->save($data);
            }
        }
    }
    public function html_trim(){
        $html='Test tested again<br><br><br><br clear="all"><br><br><br><br><br clear="all"><br> <br><br><br><br><br clear="all"><br> <br><br><br><br><br clear="all"><br> <br><br><br>';
        $pattern = '(?:[ \t\n\r\x0B\x00\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}]|&nbsp;|<br\s*\/?>)+';
        echo preg_replace('/^' . $pattern . '|' . $pattern . '$/u', '', $html);die;
        
    }


/**
 * @method: user help
 * @purpose: help desk
 * @param none
 * @return void
 **/
  public function help() {
      if ($this->request->is('post')) {
           //$this->request->data['Enquiry'] = $this->request->data['Ticket']; 
           if($this->Enquiry->save($this->request->data)){
               $this->Session->setFlash('Message was successfully sent.');
               $this->redirect(array('controller' => 'tickets', 'action' => 'help'));
           }
      }
      
      if($this->Auth->user('id')&&$this->Auth->user('indentify')=="customer"){
          $this->loadModel("Customer");
          $this->set("customer",  $this->Customer->read(null,$this->Auth->user('id')));
      }
  }

/**
 * @method: enquiry_list
 * @purpose: list of enquiries
 * @param none
 * @return void
 **/
  public function admin_enquiry_list() {
      $enquiries = $this->Enquiry->find('all');
      $this->set('enquiries', $enquiries);
  }

/**
 * @method: enquiry_view
 * @purpose: view an enquiry
 * @param none
 * @return void
 **/
  public function admin_enquiry_view($id) {
      $enquiry = $this->Enquiry->read(null, $id);
      if($enquiry['Enquiry']['read'] == 0){
          $this->Enquiry->id = $enquiry['Enquiry']['id'];
          $this->Enquiry->saveField('read', 1);
      }
      $this->set('enquiry', $enquiry);
  }
  
/**
 * @method: query_reply
 * @purpose: reply to enquiry
 * @param none
 * @return void
 **/
  public function admin_query_reply() {
      if ($this->request->is('post')) { 
           $this->request->data['EnquiryReply'] = $this->request->data['Ticket']; 
           $this->request->data['EnquiryReply']['user'] = $this->Auth->user('username');
           if($this->Enquiry->EnquiryReply->save($this->request->data)){
           
              $qID = $this->request->data['EnquiryReply']['enquiry_id'];
              $query = $this->Enquiry->find('first', array('conditions' => array('id' => $qID)));
              $array_values['CUSTOMER_NAME'] = $query['Enquiry']['name'];
              $array_values['MESSAGE_CONTENT'] = $this->request->data['EnquiryReply']['reply'];
              $email = $query['Enquiry']['email'];
              $this->SendMail->send_mail("20", $email, "Reply for Query", $array_values);
           
              $this->redirect(array('controller' => 'tickets', 'action' => 'enquiry_view', $this->request->data['Ticket']['enquiry_id']));
           }
      }
  }
  


}